package com.wp.controller;

import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.wp.common.CURDUtil;
import com.wp.common.MD5Util;
import com.wp.common.RequestUtil;

@Controller
public class RegisterController{
	private static Logger log = Logger.getLogger(RegisterController.class);
	//验证用户登陆，成功就返回成功页面，失败则返回失败页面
	@SuppressWarnings({ })
	@RequestMapping("register.do")
	public ModelAndView registerJump(HttpServletRequest req,Model model){
		return new ModelAndView("register");
	}
	
	@SuppressWarnings("rawtypes")
	@RequestMapping("registSave.do")
	public ModelAndView registSave(HttpServletRequest req,HttpServletResponse resp){
		Map param = RequestUtil.getParams(req);	
		
		try {
			JSONObject json = new JSONObject();
			resp.setContentType("application/json; charset=utf-8");  
			PrintWriter out = resp.getWriter();
			
			try{
				String md5= MD5Util.makeMode((String)param.get("pwd"));
				param.remove("pwd");
				param.put("pwd", md5);
				//将注册信息进行写表操作
				CURDUtil.insert("users.registSave", param);
				//写表成功，返回成功的标志
				json.put("resCode", "1");
				out.write(json.toString());
				if(out!=null){
					out.close();
				}
			}catch(Exception e){
				//写表失败返回失败的标识
				json.put("resCode", "2");
				out.write(json.toString());
				if(out!=null){
					out.close();
				}
				return null;
			}
		} catch (Exception e1) {
			log.error("b不支持JSON对象抛出了异常");
			return null;
		}
		return null;
	}
	
	/**
	 * @param req
	 * @return
	 * @category 校验注册的账号是否已经存在
	 */
	@RequestMapping("validUserAcc.do")
	public ModelAndView validUAcc(HttpServletRequest req,HttpServletResponse resp){
		Map param = RequestUtil.getParams(req);
		try {
			JSONObject json = new JSONObject();
			resp.setContentType("application/json; charset=utf-8");  
			PrintWriter out = resp.getWriter();
			
			try{
				//将注册信息进行写表操作
				Integer isExists = (Integer)CURDUtil.queryObject("users.selectIsExists", param);
				//写表成功，返回成功的标志
				if(isExists > 0){
					json.put("isExists", "1");//存在
				}else{
					json.put("isExists", "2");//不存在
				}
				out.write(json.toString());
				if(out!=null){
					out.close();
				}
			}catch(Exception e){
				//写表失败返回失败的标识
				json.put("resCode", "2");
				out.write(json.toString());
				if(out!=null){
					out.close();
				}
				return null;
			}
		} catch (Exception e1) {
			log.error("b不支持JSON对象抛出了异常");
			return null;
		}
		return null;
	}
}
